<template>
  <div :ref="refName" class="ww-ap-lyric-player">
    <p
      v-for="(item,key) in lyric.lyrics_all"
      :key="key"
      :style="style"
      :class="{'selected':lrcSelected==key}"
    >{{item.text}}</p>
  </div>
</template>
<script>
import Lyrics from 'lyrics.js'
export default {
  name: 'ww-ap-lyric-player',
  props: {
    lyrictxt: {
      type: String,
      required: true,
    },
    time: {
      type: Number,
      required: true,
    },
    refName: {
      type: String,
      default: 'wwaplryic',
    },
  },
  data () {
    return {
      dom: null,
      offset: 0,
      lrcSelected: -1,
      lyric: Object(),
      randered: false,
    }
  },
  computed: {
    style () {
      return 'transform:translateY(' + this.offset + 'px)'
    },
  },
  watch: {
    lyrictxt (newV, oldV) {
      this.$log.debug('wwap-lyric', newV.split('\n')[0])
      // update lyric and set rander is needed
      this.lyric = new Lyrics(this.lyrictxt)
      this.randered = false
    },
    time (newV, oldV) {
      // time maybe updates before lyrictxt
      // if lyric dom it's ready then return
      if (!this.randered) return
      this.lrcSelected = this.lyric.select(this.time)
      this.offset = this.dom.clientHeight / 2
      for (let i = 0; i < this.lrcSelected; i += 1) {
        this.offset -= this.dom.childNodes[i].scrollHeight
      }
      // this.lrcSelected can be -1, which will raise error if we do nothing
      if (this.lrcSelected >= 0) { this.offset -= this.dom.childNodes[this.lrcSelected].scrollHeight }
      this.$log.debug('wwap-lyric', 'offset', this.offset)
    },
  },
  mounted () {
    // when mouted we have lyrictxt for audio idx 0. if the first audio's idx
    // is also 0, then the watcher for lyrictxt won't be actived, we need to
    // activate it ourselves
    this.lyric = new Lyrics(this.lyrictxt)
    this.randered = false
  },
  updated () {
    this.$log.debug('wwap-lyric', this.lyrictxt.split('\n')[0])
    // if dom rander is needed in last tick
    // then dom should be ready now
    // we can set lyric dom offset
    if (!this.randered) {
      // marked rander isn't needed first
      this.randered = true
      // then do our work, reset lrcSelected and offset
      this.lrcSelected = -1
      this.dom = this.$refs[this.refName]
      // set top of the first line at half of the lyric dom
      this.offset = this.dom.clientHeight / 2
      this.$log.debug('wwap-lyric', 'offset', this.offset)
    }
  },
}
</script>
<style lang="scss">
.ww-ap-lyric-player {
  width: 100%;
  height: 100%;
  text-align: center;
  overflow: hidden;
  mask: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0) 0%,
    rgba(255, 255, 255, 1) 7%,
    rgba(255, 255, 255, 1) 92%,
    rgba(0, 0, 0, 0) 100%
  );
  p {
    padding: 2px 0;
    margin: 0;
    transition: 0.5s;
    &.selected {
      font-size: medium;
      color: #1a8bed;
    }
    &::before {
      content: "-";
      color: transparent;
    }
  }
}
</style>
